#import "PhotoPicker.h"
#import <Photos/Photos.h>
#import <UnityFramework/UnityFramework.h>
#import <objc/runtime.h>

// 在接口声明中明确遵循所需的协议
@interface PhotoPicker () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@end

@implementation PhotoPicker {
    int _maxSelection;
    UIViewController *_unityViewController;
}

+ (instancetype)sharedInstance {
    static PhotoPicker *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[PhotoPicker alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _unityViewController = UnityGetGLViewController();
        [self checkFilePermissions]; // 初始化时检查文件权限
    }
    return self;
}

- (void)openPhotoPickerWithMaxSelection:(int)maxSelection {
    _maxSelection = maxSelection;
    
    // 使用运行时检查来避免链接错误
    if (@available(iOS 14.0, *)) {
        Class phpickerClass = NSClassFromString(@"PHPickerViewController");
        if (phpickerClass) {
            [self openPHPicker];
            return;
        }
    }
    
    // iOS 14以下不支持多选，回退到单选
    [self openUIImagePicker];
}

- (void)openPHPicker {
    if (@available(iOS 14.0, *)) {
        // 使用运行时创建类实例，避免编译时链接
        Class configClass = NSClassFromString(@"PHPickerConfiguration");
        Class filterClass = NSClassFromString(@"PHPickerFilter");
        
        if (configClass && filterClass) {
            id config = [[configClass alloc] init];
            [config setValue:@(_maxSelection) forKey:@"selectionLimit"];
            
            id imagesFilter = [filterClass performSelector:NSSelectorFromString(@"imagesFilter")];
            [config setValue:imagesFilter forKey:@"filter"];
            
            Class phpickerClass = NSClassFromString(@"PHPickerViewController");
            id picker = [[phpickerClass alloc] performSelector:NSSelectorFromString(@"initWithConfiguration:") withObject:config];
            
            [picker setValue:self forKey:@"delegate"];
            
            [_unityViewController presentViewController:picker animated:YES completion:nil];
            return;
        }
    }
    
    // 如果 PHPicker 不可用，回退到 UIImagePicker
    [self openUIImagePicker];
}

- (void)openUIImagePicker {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = NO;
    
    // iOS 11+ 支持相册多选
    if (@available(iOS 11.0, *)) {
        [picker setValue:@(_maxSelection) forKey:@"imagePickerVc"];
    }
    
    [_unityViewController presentViewController:picker animated:YES completion:nil];
}

#pragma mark - PHPickerViewControllerDelegate (使用动态响应)

// 动态响应 PHPickerViewControllerDelegate 方法
- (void)performPHPPickerCompletion:(id)picker results:(NSArray *)results {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if (results.count == 0) {
        // 发送空数组表示取消选择
        [self sendImagePathsToUnity:@[]];
        return;
    }
    
    NSMutableArray *imagePaths = [NSMutableArray array];
    dispatch_group_t group = dispatch_group_create();
    
    for (id result in results) {
        id itemProvider = [result valueForKey:@"itemProvider"];
        if ([itemProvider respondsToSelector:@selector(canLoadObjectOfClass:)]) {
            dispatch_group_enter(group);
            
            [itemProvider performSelector:@selector(loadObjectOfClass:completionHandler:)
                               withObject:[UIImage class]
                               withObject:^(id object, NSError *error) {
                if ([object isKindOfClass:[UIImage class]]) {
                    UIImage *image = (UIImage *)object;
                    NSString *path = [self saveImageToTemporaryDirectory:image];
                    if (path) {
                        [imagePaths addObject:path];
                    }
                } else {
                    NSLog(@"Failed to load image object: %@", error);
                }
                dispatch_group_leave(group);
            }];
        }
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self sendImagePathsToUnity:imagePaths];
    });
}

// 动态方法解析
+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == NSSelectorFromString(@"picker:didFinishPicking:")) {
        class_addMethod([self class], sel, (IMP)dynamicPHPPickerHandler, "v@:@@");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

// 动态方法处理
static void dynamicPHPPickerHandler(id self, SEL _cmd, id picker, id results) {
    [self performPHPPickerCompletion:picker results:results];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    if (image) {
        NSString *path = [self saveImageToTemporaryDirectory:image];
        if (path) {
            [self sendImagePathsToUnity:@[path]];
        } else {
            [self sendImagePathsToUnity:@[]];
        }
    } else {
        [self sendImagePathsToUnity:@[]];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self sendImagePathsToUnity:@[]];
}

#pragma mark - Utility Methods

- (NSString *)saveImageToTemporaryDirectory:(UIImage *)image {
    @autoreleasepool {
        NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
        if (!imageData) {
            NSLog(@"Failed to convert image to JPEG data");
            return nil;
        }
        
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", [[NSUUID UUID] UUIDString]];
        NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
        
        NSError *error = nil;
        BOOL success = [imageData writeToFile:tempPath options:NSDataWritingAtomic error:&error];
        
        if (!success || error) {
            NSLog(@"Failed to save image to %@: %@", tempPath, error);
            return nil;
        }
        
        // 验证文件确实被创建
        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:tempPath];
        if (!fileExists) {
            NSLog(@"File was saved but doesn't exist at path: %@", tempPath);
            return nil;
        }
        
        // 获取文件大小
        NSError *attributesError = nil;
        NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:tempPath error:&attributesError];
        if (attributesError) {
            NSLog(@"Failed to get file attributes: %@", attributesError);
        } else {
            NSNumber *fileSize = fileAttributes[NSFileSize];
            NSLog(@"Image saved successfully at: %@, Size: %@ bytes", tempPath, fileSize);
        }
        
        return tempPath; // 返回原始文件路径，不要添加 file://
    }
}

- (void)sendImagePathsToUnity:(NSArray *)imagePaths {
    // 创建包含详细文件信息的数组
    NSMutableArray *fileInfoArray = [NSMutableArray array];
    
    for (NSString *filePath in imagePaths) {
        // 检查文件是否存在
        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
        
        if (fileExists) {
            // 获取文件属性
            NSError *error = nil;
            NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
            
            NSNumber *fileSize = fileAttributes[NSFileSize] ?: @0;
            NSString *fileName = [filePath lastPathComponent];
            
            // 创建文件信息字典
            NSDictionary *fileInfo = @{
                @"path": filePath, // 原始路径（Unity 需要这个）
                @"uri": [NSString stringWithFormat:@"file://%@", filePath], // 完整的 URI
                @"name": fileName,
                @"size": fileSize,
                @"exists": @(YES)
            };
            [fileInfoArray addObject:fileInfo];
        } else {
            NSLog(@"File does not exist at path: %@", filePath);
            
            // 即使文件不存在也发送信息，但标记为不存在
            NSDictionary *fileInfo = @{
                @"path": filePath,
                @"uri": [NSString stringWithFormat:@"file://%@", filePath],
                @"name": [filePath lastPathComponent],
                @"size": @0,
                @"exists": @(NO)
            };
            [fileInfoArray addObject:fileInfo];
        }
    }
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:fileInfoArray options:0 error:&error];
    
    if (error) {
        NSLog(@"Failed to create JSON: %@", error);
        // 发送空数组作为错误处理
        UnitySendMessage("GetPhotoIOS", "_OnPhotoPickedCallback", "[]");
        return;
    }
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"Sending to Unity: %@", jsonString);
    UnitySendMessage("GetPhotoIOS", "_OnPhotoPickedCallback", [jsonString UTF8String]);
}

- (void)checkFilePermissions {
    NSString *tempDir = NSTemporaryDirectory();
    NSError *error = nil;
    
    // 检查临时目录的写入权限
    BOOL isWritable = [[NSFileManager defaultManager] isWritableFileAtPath:tempDir];
    NSLog(@"Temporary directory is writable: %@", isWritable ? @"YES" : @"NO");
    
    if (!isWritable) {
        NSLog(@"WARNING: Temporary directory is not writable!");
    }
    
    // 列出临时目录中的文件（用于调试）
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:tempDir error:&error];
    if (error) {
        NSLog(@"Failed to list files in temp directory: %@", error);
    } else {
        NSLog(@"Files in temp directory: %@", files);
    }
    
    // 检查临时目录的完整路径
    NSLog(@"Temporary directory path: %@", tempDir);
}

- (void)cleanTemporaryDirectory {
    NSString *tempDir = NSTemporaryDirectory();
    NSError *error = nil;
    
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:tempDir error:&error];
    if (error) {
        NSLog(@"Failed to list files for cleaning: %@", error);
        return;
    }
    
    for (NSString *file in files) {
        if ([file hasSuffix:@".jpg"] || [file hasSuffix:@".jpeg"] || [file hasSuffix:@".png"]) {
            NSString *filePath = [tempDir stringByAppendingPathComponent:file];
            BOOL success = [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
            if (!success) {
                NSLog(@"Failed to remove file %@: %@", file, error);
            } else {
                NSLog(@"Removed old temporary file: %@", file);
            }
        }
    }
}

@end

// 使用条件编译确保 C++ 兼容性
#ifdef __cplusplus
extern "C" {
#endif

void _OpenPhotoPicker(int maxSelection) {
    [[PhotoPicker sharedInstance] openPhotoPickerWithMaxSelection:maxSelection];
}

// 清理临时文件的函数
void _CleanTemporaryFiles() {
    [[PhotoPicker sharedInstance] cleanTemporaryDirectory];
}

// 检查文件权限的函数
void _CheckFilePermissions() {
    [[PhotoPicker sharedInstance] checkFilePermissions];
}

#ifdef __cplusplus
}
#endif
